package tpase.KeyServer.Handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import tpase.KeyServer.Service.KeyServerSetupService;
import tpase.KeyServer.VO.Message;
import tpase.KeyServer.VO.PublicParam;
import tpase.KeyServer.VO.SecretKey;
import tpase.KeyServer.VO.StatusCode;
import tpase.util.Util;

import java.util.Map;

@ChannelHandler.Sharable
public class ServerSetupHandler extends ChannelInboundHandlerAdapter {
    private String jpbcPath;
    private String paramPath;
    private String publicParamPath;
    private String secretKeyPath;
    private KeyServerSetupService keyServerSetupService;


    public ServerSetupHandler(KeyServerSetupService keyServerSetupService, String paramPath) {
        this.keyServerSetupService = keyServerSetupService;
        this.paramPath = paramPath;
        jpbcPath = paramPath + "/a.properties";
        publicParamPath = paramPath + "/publicParam.json";
        secretKeyPath = paramPath + "/secretKey.json";
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Message request = new Message(StatusCode.SETUP_REQUEST);
        ctx.writeAndFlush(request);
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message respond = (Message) msg;

        if (respond.getStatusCode() == StatusCode.SETUP_RESPONSE) {

            Map<String, byte[]> map = respond.getMap();

            // 对 Global Server 的初始化响应数据 存储 到数据库
            keyServerSetupService.storeSi(jpbcPath, publicParamPath, map);

        }
        ctx.close();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught: 发生异常，关闭通道");
        System.out.println(cause.toString());
        // 发生异常，关闭通道
        ctx.close();
    }


}
